<?php
namespace Duobao\Controller;

use Duobao\Model\PayModel as Pay;
use Com\Weixin\Pay as WxPay;
use Think\Log;
use Duobao\Controller\LogController as MyLog;
use Com\Weixin\Pay\unit\JsApiPay as JsApiPay;

class PayController extends ControllerBase{
    /**
     * 默认
     */
    public function index()
    {
        echo "<!--hi , i'm from " . MODULE_NAME . "~" . APP_STATUS, "-->";
    }


    /**
     * 显示订单的页面，订单的页面的内容，包含支付类型，金额等
     */
    public function showPayPage(){

            $order = I('get.order');#获取订单号
            $token = I("get.token");#获取token
            #判断token是否为空，如果为空直接返回error
            if(empty($token)){
                $this->error('empty of token');
                exit;
            }else{
                $uid = $this->getUid($token);
            }
            #获取支付类型，支付uid，和支付订单
            if(!empty($order)){
                if(is_numeric($uid)){
                    $this->getPayOpenId($uid,$order,$token);

                    $model = new Pay();
                    $result = $model->payMessage($uid,$order);#显示支付信息
                    if($result){
                        $this->assign('appname',C('APP_NAME'));
                        $this->assign("front",C("FRONT_URL"));
                        $this->assign('payurl',C('payAPP_URL'));
                        $this->assign('type',$result['pay_type']);
                        $this->assign('money',$result['money']);
                        $this->assign('token',I("get.token"));
                        $this->assign('order',$order);
                        $this->display('default/message');
                    }else{
                        $this->error('订单错误');
                    }
                }else{
                    $this->error('uid 不为数字');
                }
            }else{
               $this->error('order empty');
            }

    }

    /**
     * ping显示支付提示和跳转到支付宝的接口
     */
    public function pay_tips(){
        #判断是否是来自微信浏览器，如果是显示tips连接，如果不是，跳转到支付宝
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            $this->assign('fronturl',C('FRONT_URL'));
            $this->display('default/pay_alipay');
        }else{
            $this->assign('token',I('get.token'));
            $this->assign('order',I('get.order'));
            $this->assign('chanal',I('get.chanal'));
            $this->assign('payurl',C('APP_URL'));
            $this->display('default/jump_tips');
        }
    }

    /**
    * 显示订单的页面，订单的页面的内容，包含支付类型，金额等
    */
    public function showPayPagebak(){
        $order = I('get.order');#获取订单号
        $token = I("get.token");#获取token
        #判断token是否为空，如果为空直接返回error
        if(empty($token)){
            $this->error('empty of token');
            exit;
        }else{
            $uid = $this->getUid($token);
        }

        #获取支付类型，支付uid，和支付订单
        if(!empty($order)){
            if(is_numeric($uid)){
                $model = new Pay();
                $result = $model->payMessage($uid,$order);#显示支付信息
                if($result){
                    $this->assign('appname',C('APP_NAME'));
                    $this->assign("front",C("FRONT_URL"));
                    $this->assign('payurl',C('APP_URL'));
                    $this->assign('type',$result['pay_type']);
                    $this->assign('money',$result['money']);
                    $this->assign('token',I("get.token"));
                    $this->assign('order',$order);
                    #判断订单的支付类型
                    if($result['pay_type'] == '帐户余额支付'){
                        $this->display('default/message');
                    }else{
                        $this->display('default/message2');
                    }

                }else{
                    $this->error('订单错误');
                }
            }else{
                $this->error('uid 不为数字');
            }
        }else{
            $this->error('order empty');
        }

    }

    /**
     * 统一支付接口
     */
    public function Pay2(){
        $order = I('post.order');
        $uid = $this->getUid(I('get.token'));
        $chanal = I('post.chanal');

        if(!empty($order)){
            if(is_numeric($uid)){
                $model = new Pay();
                $result = $model->Pay2($uid,$order,$chanal);
                if($result){
                    if($result['type'] == 'balances'){
                        if($result['status'] == true){
//                            $this->success('余额支付成功');
                            #MyLog::write('true');
                            return $this->response($result);
                        }else{
                            $result['status'] = false;
                            return $this->response($result);
                        }
                    }else{
                        return $this->response($result);
                    }
                }else{
                 $this->error('支付失败');
                }
            }else{
                $this->error($uid);
            }
        }else{
            $this->error('empty od order');
        }
    }

    /**
     * 余额支付
     */
    public function Pay(){
        $order = I('post.order');
        $uid = $this->getUid(I('get.token'));

        if(!empty($order)){
            if(is_numeric($uid)){
                $model = new Pay();
                $result = $model->Pay($uid,$order);
                if($result){
                    if($result['type'] == 'balances'){
                        if($result['status'] == true){
//                            $this->success('余额支付成功');
                            #MyLog::write('true');
                            return $this->response($result);
                        }else{
                            $result['status'] = false;
                            return $this->response($result);
                        }
                    }else{
                        return $this->response($result);
                    }
                }else{
                    $this->error('支付失败');
                }
            }else{
                $this->error($uid);
            }
        }else{
            $this->error('empty od order');
        }
    }
    /**
     * 支付宝支付成功回调，一般用于
     */
    public function ping_success(){
        $this->assign('title',C('APP_NAME'));
        $this->assign('wx_id',C('wx_id'));
        $this->display('default/pay_success');
    }

    /**
     * 支付取消的回调
     */
    public function ping_cancle(){
        $this->assign('title',C('APP_NAME'));
        $this->assign('wx_id',C('wx_id'));
        $this->display('default/pay_cancle');
    }


    /**
     * 获取支付微信号的用户所对应的openid
     */
    private function getPayOpenId($uid,$order,$token){
        #修改逻辑
        $model = new \Think\Model();
        $condition['wxhao'] = C('paywxhao');
        $condition['uid'] = $uid;
        $payOpenidExist = $model->table('__OPENID__')->where($condition)->find();

        if($payOpenidExist){
            return ;
        }else{
            header('Location:'.C('payAPP_URL').'/Pay/insertOpenid?token='.$token.'&order='.$order.'&jump='.urlencode(C('APP_URL')));
            exit(0);
        }
    }

    /**
     * 插入用户的支付的openid
     */
    public function insertOpenid(){

        $uid = $this->getUid(I('get.token'));
        $token = I('get.token');
        $order = I('get.order');
        $jump = urldecode(I('get.jump'));

        #判断uid在数据库中是否存在
        $model = new \Think\Model();
        $condition['$uid'] = $uid;
        $uidExist = $model->table('__MEMBER__')->where($condition)->find();

        if(!$uidExist){
            $this->error('Uid 不存在',C('FRONT_URL'));
        }

        $jsapi = new JsApiPay();
        $openId = $jsapi->GetOpenid(2);

        if(empty($openId)){
            MyLog::write('获取主支付账户的用户的openid失败,weixinmodel,line:139,uid:'.$uid);
            return ;
        }
        #插入opneid
        $data['uid'] = $uid;
        $data['openid'] = $openId;
        $data['wxhao'] = C('paywxhao');
        $data['addtime'] = date('Y-m-d H:i:s',time());
        $data['updatetime'] = $data['addtime'];
        $insertResult = $model->table('__OPENID__')->add($data);
        if(!$insertResult){
            MyLog::write('weixinModel----line:90,getPayOpenId');
        }

        $var = 'Location:'.$jump.'/Pay/showPayPage?token='.$token.'&order='.$order;
        #插入完成之后回跳
        header($var);
        # MyLog::write($var);

        exit(0);
    }

    /**
     * 余额支付,私有
     */
    private function balancesPay($uid,$order){
        $model = new Pay();

        #返回支付结果，如果支付成功返回true，否则返回false
        return $model->balancesPay($uid,$order);
    }

    /**
     * 微信支付，不通过路由，因为微信支付成功的通知方式是回调
     */
    public function notify(){
            #MyLog::write('进入微信回调');
            $pay = new WxPay();
            $pay->notify( array($this,'weixin_callback'), $msg);
            if( $msg ) {
                Log::write('微信支付回调，签名错误:' . $msg);
            }
    }

    public function weixin_callback( $result )
    {

        $model  = new Pay();

        try{
            $result_code = $result['result_code'];
            if(  $result_code =="SUCCESS") {
                $out_trade_no = $result['out_trade_no'];
                $total_fee = $result['total_fee'];
                $transaction_id = $result['transaction_id'];
                #MyLog::write($out_trade_no.":".$total_fee.":".$transaction_id);
                $result =$model->wxNotify($out_trade_no,$total_fee,$transaction_id);

                if(!$result){
                    E('订单异常',500);
                }
            }else{
                E($result['return_msg'],500);
            }
        }catch( \Exception $e ){
            $this->weixin_replay( false ,$e->getMessage());
            return ;
        }

        $this->weixin_replay( true , '' );
    }

    /**
     * 回复腾讯的回调
     * @param string $is_ok
     * @param string $msg
     */
    private function weixin_replay( $is_ok = true , $msg = "")
    {
        $is_ok = $is_ok ? 'SUCCESS' : "FAIL";
        $txt = <<<EOT
        <xml>
  <return_code><![CDATA[{$is_ok}]]></return_code>
  <return_msg><![CDATA[{$msg}]]></return_msg>
</xml>
EOT;
        echo $txt;
    }


    /**
     * 测试产生幸运号码
     */
    public function testLuckly(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = '';
        $ret['data'] = array();

        try{
            $model = new Pay();
            $ret['data'] = $model->productLucklyNumber(12,'1443088531');
        }catch (\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }

        return $this->response($ret);
    }
    /* end of pay controller*/
}